<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>市级多样化宣讲队</span>
      </div>
    </template>
    
    <div class="search-form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="formInline.name" placeholder="请输入宣讲队名称" clearable @keyup.enter="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.responsibleUnit" placeholder="请输入责任单位" clearable @keyup.enter="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="addCity">新建</el-button>
      </div>
    </div>

    <div class="table-data" v-loading="loading">
      <el-table
        :data="cityData"
        stripe
        borderresizable
        highlight-hover-row
        show-overflow
        keep-source
        scrollbar-always-on
      >
        <el-table-column
          v-for="(tableItem, tableIndex) in cityTableColumns" :key="tableIndex"
          :prop="tableItem.field"
          :label="tableItem.label"
          :min-width="tableItem.minWidth"
          :formatter="tableItem.formatter"
          :show-overflow-tooltip="tableItem.field != 'coverUrl'"
        >
          <template #default="scope" v-if="tableItem.slot">
            <slot :name="tableItem.slot" v-bind="scope">
              <el-image class="table-item-img" :src="reFileResult(scope.row.coverUrl)" fit="cover">
                <template #error>
                  <div class="image-slot">
                    <el-image style="width: 200px;" src="/images/course_default.png" fit="cover" />
                  </div>
                </template>
              </el-image>
            </slot>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          field="opera"
          label="操作"
          min-width="220"
        >
          <template #default="{ row }">
            <el-button
              type="warning"
              link
              @click="cityDetail(row)"
            >查看</el-button>
            <el-button
              type="warning"
              link
              @click="cityMember(row)"
            >管理宣讲队成员</el-button>
            <el-button
              type="success"
              link
              @click="cityEdit(row)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-page">
        <el-pagination background layout="prev, pager, next" :total="dataTotal" :page-size="pageSize" :current-page="currentPage" @current-change="currentChange" />
      </div>
    </div>

    <!-- 宣讲队成员列表弹窗 -->
    <el-dialog v-model="dialogTableVisible" title="宣讲队成员">
      <el-button type="primary" @click="addMemberClick" style="margin-bottom: 16px;">新增宣讲队成员</el-button>
      <div class="table-data" v-loading="memberLoading">
        <el-table :data="memberList" style="height: 300px;">
          <el-table-column property="name" label="成员名称" width="150" />
          <el-table-column property="mobile" label="手机号" width="200" />
          <el-table-column property="unit" label="单位" />

          <el-table-column
            field="opera"
            label="操作"
            min-width="120"
          >
            <template #default="{ row }">
              <el-button
                type="warning"
                link
                @click="deleteMember(row)"
              >删除</el-button>
              <el-button
                type="success"
                link
                @click="editMember(row)"
              >编辑</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="table-page">
          <el-pagination background layout="prev, pager, next" :total="memberTotal" :page-size="memberPageSize" :current-page="memberPageIndex" @current-change="memberCurrentChange" />
        </div>
      </div>
    </el-dialog>

    <!-- 新增、编辑宣讲队成员弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="成员信息">
      <el-form :model="memberForm" ref="memberFormRef" label-width="100px" :rules="memberRules">
        <el-form-item label="成员名称" prop="name">
          <el-input v-model="memberForm.name" placeholder="请输入成员名称" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="memberForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="memberForm.unit" placeholder="请输入单位" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="addMember">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
export default { name: "backendPublicizeCity" }
</script>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/http/index';
import { dateFormatter, reFileResult } from "@/utils/backend.js"
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const route = useRouter();

onMounted(() => {
  onSubmit()
})

/* 搜索表单 */
const formInline = ref({
  name: "",
  responsibleUnit: "",
})

/* 分页 */
const dataTotal = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

if(route.currentRoute.value.query.currentPage) {
  currentPage.value = Number(route.currentRoute.value.query.currentPage)
}

/* 切换页码方法 */
const currentChange = (val) => {
  currentPage.value = val
  onSubmit()
}

/* 表格数据加载动画 */
const loading = ref(false)

/* 表格数据 */
const cityData = ref([])

/* 表格字段 */
const cityTableColumns = reactive([
  { field: "name", label: "宣讲队名称", minWidth: "120" },
  { field: "responsibleUnit", label: "责任单位", minWidth: "120" },
  { field: "creationTime", label: "成立时间", minWidth: "120", formatter: dateFormatter },
  { field: "memberShip", label: "成员情况", minWidth: "120" },
  { field: "preachObject", label: "宣讲对象", minWidth: "250" },
  { field: "coverUrl", label: "封面", minWidth: "250", slot: "imgView" },
  { field: "longitude", label: "经度", minWidth: "120" },
  { field: "latitude", label: "纬度", minWidth: "120" },
  { field: "area", label: "区划", minWidth: "120" },
])

/* 列表筛选 */
const onSubmit = () => {
  loading.value = true
  let params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  let dfi = {
    Logic: 0,
    Filters: []
  }

  for (let k in formInline.value){
    if(formInline.value[k]){
      dfi.Filters.push({
        Field: k,
        Operator: 0,
        Value: formInline.value[k]
      })
    }
  }

  if(dfi.Filters.length){
    params.dfi = dfi
  }
  http.$POST("/PreachM/GetPreachTeamInfoList", params).then(res => {
    loading.value = false
    if (res.isError) return
    cityData.value = res.result.dataLst
    dataTotal.value = res.result.countAll
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败，请重试")
  })
}

/* 点击新建 */
const addCity = () => {
  route.push({
    path: "/backend/publicize-city/add",
    query: { type: 'add' }
  })
}

/* 点击编辑 */
const cityEdit = (row) => {
  route.push({
    path: "/backend/publicize-city/add",
    query: { id: row.id, type: 'edit', currentPage: currentPage.value }
  })
}

/* 点击查看详情 */
const cityDetail = (row) => {
  let { href } = route.resolve({
    path: "/backend/publicize-city/detail",
    query: { id: row.id, currentPage: currentPage.value }
  })
  window.open(href, "_blank")
}

/* 宣讲队成员弹窗 */
const dialogTableVisible = ref(false)

/* 宣讲队成员列表 */
const memberLoading = ref(false)
const memberList = ref([])
const memberTotal = ref(0)
const memberPageIndex = ref(1)
const memberPageSize = ref(10)

/* 点击管理成员按钮 */
const cityMember = (row) => {
  memberForm.value.preachTeamId = row.id
  dialogTableVisible.value = true
  getMemberList()
}

/* 切换分页 */
const memberCurrentChange = (val) => {
  memberPageIndex.value = val
  getMemberList()
}

/* 查询成员列表 */
const getMemberList = () => {
  memberLoading.value = true
  let params = {
    pageIndex: memberPageIndex.value,
    pageSize: memberPageSize.value,
    dfi: {
      Logic: 0,
      Filters: [{
        Field: 'preachTeamId',
        Operator: 8,
        Value: memberForm.value.preachTeamId
      }]
    }
  }
  http.$POST("/PreachM/GetPreachMemberInfoList", params).then(res => {
    memberLoading.value = false
    if(res.isError) return
    memberList.value = res.result.dataLst
  }).catch(err => {
    memberLoading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 新增成员 */
const dialogFormVisible = ref(false)
const memberFormRef = ref(null)
const memberForm = ref({
  preachTeamId: "",
  name: "",
  mobile: "",
  unit: "",
})


const validatePhoneNum = (_, value, callback) => {
  // 判断是否为空  
  if (!value) callback(new Error('请输入成员联系电话'))
  // 判断手机号格式是否正确  
  const regex = /^1[3-9]\d{9}$/; // 中国手机号的正则表达式  
  if (!regex.test(value)) {
    callback(new Error('手机号格式不正确'))
  }
  callback()
}

const memberRules = ref({
  name: [
    { required: true, message: '请输入成员姓名', trigger: 'blur' },
  ],
  mobile: [
    { required: true, validator: validatePhoneNum, trigger: 'blur' },
  ],
  unit: [
    { required: true, message: '请输入成员单位', trigger: 'blur' },
  ],
})

/* 点击新增成员 */
const addMemberClick = () => {
  dialogFormVisible.value = true;
  if(memberForm.value.id) {
    delete memberForm.value.id
  }
}

/* 点击编辑成员 */
const editMember = (row) => {
  dialogFormVisible.value = true
  http.$GET(`/PreachM/GetPreachMemberDetailById?Id=${row.id}`).then(res => {
    if(res.isError) return
    /* 赋值 */
    Object.keys(memberForm.value).forEach((key)=>{
      if(res.result[key] != null){
        memberForm.value[key] = res.result[key];
      }
    })
    memberForm.value.id = res.result.id
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 点击确定 */
const addMember = () => {
  console.log(memberForm.value)
  memberFormRef.value.validate((valid, fields) => {
    if(valid) {

      http.$POST("/PreachM/AddOrUpdatePreachMemberInfo", {...memberForm.value}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        if (res.IsError) {
          ElMessage.warning('操作失败');
        }else {
          ElMessage.success('操作成功');
          memberFormRef.value.resetFields()
          dialogFormVisible.value = false
          getMemberList()
        }
      }).catch(err => {
        ElMessage.warning('操作失败');
      })
    }else{
      ElMessage.warning("请先完成必填项")
    }
  })
  
}

/* 点击删除成员 */
const deleteMember = (row) => {
  ElMessageBox.confirm(
    '确定要删除此条数据吗？',
    '请确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    http.$POST(`/PreachM/DelPreachMemberById?Id=${row.id}`).then(res => {
      if(res.IsError) {
        ElMessage.warning("操作失败")
      }else {
        ElMessage.success("操作成功")
        dialogFormVisible.value = false
        getMemberList()
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
  
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>